package com.lujieni.msg.provider.service;

import com.lujieni.msg.provider.dao.LocalEventDao;
import com.lujieni.msg.common.properties.rabbitmq.CommonMqQueueProperties;
import com.lujieni.msg.common.properties.rabbitmq.RabbitMqQueueMapProperties;
import com.lujieni.msg.provider.po.LocalEventPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class JobService {

    @Autowired
    private LocalEventDao localEventDao;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RabbitMqQueueMapProperties rabbitMqQueueMapProperties;

    @Async
    @Transactional
    public void scanLocalEventThenSendMQ(Date startTime, Date endTime){
        List<LocalEventPO> localEventPOS = localEventDao.selectNeedData(startTime, endTime);
        localEventPOS.forEach(e->{
            e.setStatus(1);
            e.setModifyTime(new Date());
            localEventDao.updateByPrimaryKeySelective(e);
            localEventSendMq(e);
        });
    }

    private void localEventSendMq(LocalEventPO po){
        CommonMqQueueProperties commonMqQueueProperties = rabbitMqQueueMapProperties.getQueueMap().get("local-event");
        try {
            rabbitTemplate.convertAndSend(commonMqQueueProperties.getExchangeName(), commonMqQueueProperties.getRoutingKey(), po);
        } catch (Exception e) {
            /*
                如果mq没有启动或者密码输错都会进入这个异常
                但routingKey输错或者exchangeName没找到不会进入
             */
            log.error("localEventSendMq error:", e);
            throw new RuntimeException("localEventSendMq error");
        }
    }



}
